package com.pearadmin.modules.sys.controller.manage;

import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageInfo;
import com.pearadmin.common.config.proprety.TemplateProperty;
import com.pearadmin.common.constant.ControllerConstant;
import com.pearadmin.common.tools.SecurityUtil;
import com.pearadmin.common.tools.SequenceUtil;
import com.pearadmin.common.tools.string.Convert;
import com.pearadmin.common.web.base.BaseController;
import com.pearadmin.common.web.domain.request.PageDomain;
import com.pearadmin.common.web.domain.response.Result;
import com.pearadmin.common.web.domain.response.module.ResultTable;
import com.pearadmin.modules.sys.domain.AnodeCode;
import com.pearadmin.modules.sys.domain.SysUser;
import com.pearadmin.modules.sys.domain.dto.AnodeCodeDto;
import com.pearadmin.modules.sys.service.IAnodeCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 阳极编号Controller
 *
 * @author Mr.Ling
 * @date 2021-11-26
 */
@RestController
@Api(tags = {"阳极编号管理"})
@RequestMapping(ControllerConstant.API_MANAGE_PREFIX + "anodeCode")
public class AnodeCodeController extends BaseController {
    private String prefix = "manage/anodeCode" ;

    @Autowired
    private IAnodeCodeService anodeCodeService;
    @Resource
    private TemplateProperty uploadProperty;

    @GetMapping("/main")
    @PreAuthorize("hasPermission('/manage/anodeCode/main','manage:anodeCode:main')")
    public ModelAndView main() {
        return jumpPage(  prefix+"/main");
    }

    /**
     * 查询阳极编号列表
     */
    @ResponseBody
    @ApiOperation("列表")
    @GetMapping("/data")
    @PreAuthorize("hasPermission('/manage/anodeCode/data','manage:anodeCode:data')")
    public ResultTable list(@ModelAttribute AnodeCode anodeCode, PageDomain pageDomain) {
        PageInfo<AnodeCode> pageInfo = anodeCodeService.selectAnodeCodePage(anodeCode, pageDomain);
        return pageTable(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 新增阳极编号
     */
    @GetMapping("/add")
    @PreAuthorize("hasPermission('/manage/anodeCode/add','manage:anodeCode:add')")
    public ModelAndView add() {
        return jumpPage(prefix + "/add");
    }

    /**
     * 新增保存阳极编号
     * BHY100001-BHY199999
     * BHY900001-BHY999999
     */
    @ResponseBody
    @ApiOperation("新增")
    @PostMapping("/save")
    @PreAuthorize("hasPermission('/manage/anodeCode/add','manage:anodeCode:add')")
    public Result save(@RequestBody AnodeCodeDto dto) throws IOException {
        SysUser sysUser = (SysUser) SecurityUtil.currentUserObj();
        String workShopPrefix = dto.getWorkShopPrefix();
        Integer endNo = dto.getEndNo();
        Integer startNo = dto.getStartNo();
        Integer startWorkShop = dto.getStartWorkShop();
        Integer endWorkShop = dto.getEndWorkShop();
        if (startWorkShop>endWorkShop) {
           return  Result.failure("开始车间不能大于结束车间");
        }
        if (startNo>endNo) {
            return  Result.failure("开始编号不能大于结束编号");
        }
        int flag = 1;
        for (int i = startWorkShop; i <=endWorkShop ; i++) {
            for (int j = startNo; j <=endNo; j++) {
                String code = workShopPrefix + i + String.format("%05d", j);
                // 如果发现有重复的编号，那么跳出此次新增流程，继续下一个新增流程
                if (anodeCodeService.selectByCode(code) != null) {
                    continue;
                }
                AnodeCode anodeCode = new AnodeCode();
                anodeCode.setId(SequenceUtil.makeStringId());
                anodeCode.setCreateBy(sysUser.getUserId());
                anodeCode.setCreateName(sysUser.getRealName());
                anodeCode.setCreateTime(LocalDateTime.now());
                anodeCode.setCode(code);
                File touch = FileUtil.touch("C:\\home\\uploads\\qrcode.jpg");
                String qrCodePath = touch.getAbsolutePath();
                int result = anodeCodeService.insertAnodeCode(anodeCode, qrCodePath);
                //如果插入失败，那么flag结果就是0，反之是1
                flag = flag * result;
            }
        }
        return Result.decide(flag==1);
    }

    /**
     * 修改阳极编号，需要重新生成二维码 todo 重新生成二维码
     */
    @GetMapping("/edit")
    @PreAuthorize("hasPermission('/manage/anodeCode/edit','manage:anodeCode:edit')")
    public ModelAndView edit(String id, ModelMap mmap) {
        AnodeCode anodeCode = anodeCodeService.selectAnodeCodeById(id);
        anodeCode.setUpdateTime(LocalDateTime.now());
        mmap.put("anodeCode", anodeCode);
        return jumpPage(prefix + "/edit");
    }

    /**
     * 修改保存阳极编号
     */
    @ResponseBody
    @ApiOperation("更新")
    @PutMapping("/update")
    @PreAuthorize("hasPermission('/manage/anodeCode/edit','manage:anodeCode:edit')")
    public Result update(@RequestBody AnodeCode anodeCode) {
        SysUser sysUser = (SysUser) SecurityUtil.currentUserObj();
        anodeCode.setUpdateTime(LocalDateTime.now());
        anodeCode.setUpdateBy(sysUser.getUserId());
        anodeCode.setUpdateName(sysUser.getUsername());
        return decide(anodeCodeService.updateAnodeCode(anodeCode));
    }

    /**
     * 删除阳极编号
     */
    @ResponseBody
    @ApiOperation("批量刪除")
    @DeleteMapping("/batchRemove")
    @PreAuthorize("hasPermission('/manage/anodeCode/remove','manage:anodeCode:remove')")
    public Result batchRemove(String ids) {
        return decide(anodeCodeService.deleteAnodeCodeByIds(Convert.toStrArray(ids)));
    }

    /**
     * 删除
     */
    @ResponseBody
    @ApiOperation("根据id 刪除")
    @DeleteMapping("/remove/{id}")
    @PreAuthorize("hasPermission('/manage/anodeCode/remove','manage:anodeCode:remove')")
    public Result remove(@PathVariable("id") String id) {
        return decide(anodeCodeService.deleteAnodeCodeById(id));
    }
}
